<template>
	<view class="container">
		<view class="header">
			<text class="system-name">ERP进销存系统</text>
			<!-- 分段器 -->
			<view class="segment-control">
				<uni-segmented-control :current="currentSegment" :values="['前台收银', '后端管理']" @clickItem="onSegmentChange"
					activeColor="#4cd964" style=""></uni-segmented-control>
			</view>

			<view class="header-controls">
				<view v-if="isLoggedIn" class="user-info">
					<text class="username">{{ userInfo.username }}</text>
					<button @click="logout" size="mini" class="logout-button">退出</button>
				</view>
				<view v-else class="login-button-container">
					<button @click="goToLogin" size="mini">登录</button>
				</view>
			</view>
		</view>

		<view class="body">
			<!-- 前台收银的侧边栏 -->
			<view class="sidebar" v-if="currentSegment === 0">
				<view class="menu-item" @click="selectPage('activate_card')">
					<text class="icon">&#x1F4B3;</text> 开卡
				</view>
				<view class="menu-item" @click="selectPage('recharge')">
					<text class="icon">&#x1F4B5;</text> 充值
				</view>
				<view class="menu-item" @click="selectPage('Prescription')">
					<text class="icon">&#x1F465;</text> 开方
				</view>
				<view class="menu-item" @click="selectPage('secondary_card')">
					<text class="icon">&#x1F4AA;</text> 充次
				</view>
				<view class="menu-item" @click="selectPage('f_ordel_list')">
					<text class="icon">&#x1F4D1;</text> 订单列表
				</view>
				<view class="menu-item" @click="selectPage('deduction_times')">
					<text class="icon">&#x1F4C8;</text> 扣次
				</view>
				<view class="menu-item" @click="selectPage('menber_user')">
					<text class="icon">&#x1F465;</text> 会员
				</view>


			</view>

			<!-- 后端管理的侧边栏 -->
			<view class="sidebar" v-if="currentSegment === 1">
				<!-- 一级菜单项 -->
				<view v-for="menu in primaryMenus" :key="menu.id">
					<view class="menu-item" @click="toggleMenu(menu.id)">

						<text class="icon" v-html="menu.icon"></text> {{ menu.name }}

						<text v-if="menus[menu.id]" class="expand-icon">-</text>
						<text v-else class="expand-icon">+</text>
					</view>
					<!-- 二级菜单项 -->
					<view v-if="menus[menu.id]" class="submenu">
						<view v-for="submenu in secondaryMenus.filter(sub => sub.parent_id === menu.id)"
							:key="submenu.id" class="menu-item" @click="selectPage(submenu.title)">
							{{ submenu.name }}
						</view>
					</view>
				</view>
			</view>

			<view class="main-content">
				<view v-if="currentSegment === 1">
					<view style="background-color: #fff; padding: 20px; display: flex; justify-content: space-between;">
						<uni-breadcrumb separator="/" style="width: 90%;">
							<uni-breadcrumb-item v-for="(route, index) in routes" :key="index">
								{{ route.name }}
							</uni-breadcrumb-item>
						</uni-breadcrumb>
						<button @click="refreshPage" class="refresh-button" size="mini" >刷新</button>
					</view>
					
				</view>
				<view>
					<!-- 动态加载组件 -->
					<component :is="currentComponent" />
				</view>
			</view>


		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapActions
	} from 'vuex';
	import erpStats from '@/pages/erpStats/erpStats.vue'; // 统计页
	import MemberList from '@/pages/memberList/memberList.vue'; // 会员列表
	import MemberStats from '@/pages/memberList/memberStats.vue'; // 会员等级
	import MemberDetails from '@/pages/memberList/member_details.vue';
	import productslist from '@/pages/product_List/productslist.vue'; // 商品列表
	import ProductCategoryList from '@/pages/product_List/ProductCategoryList.vue'; // 商品分类
	import new_unit_added from '@/pages/product_List/new_unit_added.vue'; // 新增单位
	import order_details from '@/pages/order_List/order_details.vue'; // 订单列表
	import order_List from '@/pages/order_List/order_List.vue'; // 订单列表
	import stockOverview from '@/pages/stockOverview/stockOverview.vue'; // 库存列表
	import procurement from '@/pages/stockOverview/procurement.vue'; // 库存进货
	import supplier from '@/pages/stockOverview/supplier.vue'; // 商品补货
	import adjustment from '@/pages/stockOverview/adjustment.vue'; // 商品调货
	import personal_data from '@/pages/Store_Management/personal_data.vue'; // 个人资料
	import store_information from '@/pages/Store_Management/store_information.vue'; // 门店资料
	import Store_Management from '@/pages/Store_Management/Store_Management.vue'; // 连锁门店
	import doctors from '@/pages/Store_Management/doctors.vue'; // 医生列表

	import print_Settings from '@/pages/Store_Management/print_Settings.vue'; // 打印设置
	import device_management from '@/pages/Store_Management/device_management.vue'; // 设备管理
	import userRoles from '@/pages/userRoles/userRoles'; // 用户角色
	import accessControl from '@/pages/userRoles/accessControl.vue'; // 访问控制
	import salesData from '@/pages/salesData/salesData'; // 销售数据
	import customerAnalytics from '@/pages/salesData/customerAnalytics.vue'; // 客户分析
	import campaigns from '@/pages/campaigns/campaigns'; // 营销活动
	import discounts from '@/pages/campaigns/discounts.vue'; // 折扣优惠
	import generalSettings from '@/pages/generalSettings/generalSettings'; // 导出报表
	import paymentSettings from '@/pages/generalSettings/paymentSettings.vue'; // 数据备份
	import saveSetting from '@/pages/generalSettings/saveSetting'; // 导出报表
	import wechatSettings from '@/pages/generalSettings/wechatSettings.vue'; // 数据备份

	import activate_card from '@/pages/front_end/activate_card.vue'; // 
	import recharge from '@/pages/front_end/recharge.vue'; // 
	import secondary_card from '@/pages/front_end/secondary_card.vue'; // 
	import f_ordel_list from '@/pages/front_end/f_ordel_list.vue'; // 
	import deduction_times from '@/pages/front_end/deduction_times.vue'; // 
	import menber_user from '@/pages/front_end/menber_user.vue'; // 
	import Prescription from '@/pages/front_end/Prescription.vue'; // 开药方



	const breadcrumbs = {
		MemberList: ["首页", "会员管理", "会员列表"],
		MemberStats: ["首页", "会员管理", "会员等级"],
		MemberDetails: ["首页", "会员管理", "会员详情"],
		productslist: ["首页", "商品管理", "商品列表"],
		ProductCategoryList: ["首页", "商品管理", "商品分类"],
		new_unit_added: ["首页", "商品管理", "新增单位"],
		personal_data: ["首页", "门店管理", "个人资料"],
		store_information: ["首页", "门店管理", "门店资料"],
		Store_Management: ["首页", "门店管理", "连锁门店"],
		doctors: ["首页", "门店管理", "医生列表"],


		print_Settings: ["首页", "门店管理", "打印设置"],
		device_management: ["首页", "门店管理", "设备管理"],
		stockOverview: ["首页", "库存管理", "库存列表"],
		order_List: ["首页", "订单管理", "订单列表"],
		order_details: ["首页", "订单管理", "订单详情"],
		supplier: ["首页", "库存管理", "供应商"],
		adjustment: ["首页", "库存管理", "库存调货"],
		procurement: ["首页", "库存管理", "库存进货"],
		userRoles: ["首页", "权限管理", "用户角色"],
		accessControl: ["首页", "权限管理", "访问控制"],
		salesData: ["首页", "统计分析", "销售数据"],
		customerAnalytics: ["首页", "统计分析", "客户分析"],
		campaigns: ["首页", "营销中心", "营销活动"],
		discounts: ["首页", "营销中心", "折扣优惠"],
		generalSettings: ["首页", "系统设置", "设置"],
		paymentSettings: ["首页", "系统设置", "收款设置"],
		saveSetting: ["首页", "系统设置", "存储设置"],
		wechatSettings: ["首页", "系统设置", "微信设置"]
	};

	export default {
		data() {
			return {
				currentComponent: erpStats,
				routes: [{
						name: '首页'
					},
					{
						name: 'ERP'
					},
					{
						name: '系统统计'
					},
				],
				isLoggedIn: true,
				menus: {},
				menuData: [],
				primaryMenus: [],
				secondaryMenus: [],
				currentSegment: 0, // 当前分段器索引
				isLoggedIn: false,
				userInfo: {}
			};
		},
		components: {
			erpStats, //统计页
			MemberList, //会员列表
			MemberStats, //会员等级
			MemberDetails, //会员详情
			personal_data, //个人资料
			store_information, //门店资料
			Store_Management, //连锁门店
			doctors, //医生列表

			print_Settings, //打印设置
			device_management, //设备管理
			productslist, //商品列表
			ProductCategoryList, //商品分类
			new_unit_added, //新增单位
			stockOverview, //库存概览
			order_List, //订单列表
			order_details, //订单详情
			supplier, //供应商
			procurement, //库存进货
			adjustment, //库存调货
			userRoles, //用户角色
			accessControl, //访问控制
			customerAnalytics,
			salesData,
			campaigns,
			discounts,
			generalSettings,
			paymentSettings,
			saveSetting,
			wechatSettings,
			activate_card,
			recharge,
			secondary_card,
			f_ordel_list,
			deduction_times,
			menber_user,
			Prescription


		},
		methods: {
			async fetchMenus() {

				const res = await this.$myRuquest({
					url: '/index/plugin.users/get_user_menus',
					method: 'POST',
					data: {
						user_id: this.userInfo.user_id,

					}
				});

				if (res.data.code === 200) {
					this.menuData = res.data.data;
					this.initMenus();
				} else {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 2000
					});
				}
			},
			initMenus() {
				this.primaryMenus = this.menuData.filter(menu => menu.parent_id === 1); // 过滤出一级菜单
				this.secondaryMenus = this.menuData.filter(menu => menu.parent_id > 1 && menu.parent_id <= 10); // 过滤出二级菜单
			},
			checkLoginStatus() {
				const token = uni.getStorageSync('token');

				if (token) {
					this.isLoggedIn = true;
					this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
					this.fetchMenus();
				} else {
					this.isLoggedIn = false;
					this.userInfo = {};
					this.$router.push('/pages/login/login');
				}
			},
			goToLogin() {
				this.$router.push({
					path: '/pages/login/login'
				});
			},
			onSegmentChange(e) {
				this.currentSegment = e.currentIndex;
			},
			switchComponent(componentName) {
				this.currentComponent = componentName;
			},
			selectPage(componentName) {

				this.currentComponent = componentName;
				if (breadcrumbs[componentName]) {
					this.routes = breadcrumbs[componentName].map(name => ({
						name
					}));
				} else {
					this.routes = [{
						name: '首页'
					}];
				}
			},
			toggleMenu(menuId) {
				this.$set(this.menus, menuId, !this.menus[menuId]);
			},
			logout() {
				uni.removeStorageSync('token');
				uni.removeStorageSync('userInfo');
				this.isLoggedIn = false;
				this.userInfo = {};
				this.$router.push('/pages/login/login');
			},
			refreshPage() {
				// 重新设置currentComponent来触发组件刷新
				const current = this.currentComponent;
				this.currentComponent = null;
				this.$nextTick(() => {
					this.currentComponent = current;
				});
			}
		},
		created() {
			this.checkLoginStatus();
			this.$bus.$on('login', this.checkLoginStatus);
			this.$bus.$on('logout', this.logout);

		},
		watch: {
			isLoggedIn(newVal) {
				if (!newVal) {
					this.$router.push('/pages/login/login');
				}
			}
		}
	};
</script>

<style>
	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #2c3e50;
		color: white;
		padding: 10px 20px;
	}

	.system-name {
		font-size: 20px;
	}

	.header-controls button {
		margin-left: 10px;
		background-color: #34495e;
		color: white;
		border: none;
		padding: 8px 16px;
		cursor: pointer;
	}

	.header-controls button:hover {
		background-color: #1abc9c;
	}

	.segment-control {
		margin-left: 20px;
		width: 40%;

	}

	.body {
		display: flex;
		flex: 1;
		/* 使用剩余空间 */
	}

	.sidebar {
		width: 200px;
		background-color: #2c3e50;
		color: white;
		padding: 10px;
		overflow: auto;
		/* Allows scrolling */
		height: calc(100% - 40px);
		/* Adjust sidebar height */
	}

	.main-content {
		flex: 1;
		margin: 10px;
		overflow-y: auto;
		background-color: #ecf0f1;
	}

	.menu-item {
		margin: 10px 0;
		padding: 10px;
		background-color: #34495e;
		cursor: pointer;
		position: relative;
	}

	.menu-item:hover {
		background-color: #1abc9c;
	}

	.expand-icon {
		position: absolute;
		right: 10px;
	}

	.icon {
		margin-right: 5px;
	}

	.submenu {
		background-color: #2c3e50;
		padding-left: 20px;
	}

	.user-info {

		display: flex;
		align-items: center;
	}

	.username {

		margin-right: 10px;
	}

	.logout-button {

		background-color: #ff4d4f;
		color: #fff;
		border: none;
		padding: 8px 16px;
		border-radius: 4px;
		cursor: pointer;
	}

	.logout-button:hover {

		background-color: #e43e3e;
	}

	.login-button-container {

		display: flex;
		align-items: center;
	}

	.refresh-button {
		background-color: #4cd964;
		color: white;
		border: none;
		padding: 8px 16px;
		cursor: pointer;
		border-radius: 4px;
	}

	.refresh-button:hover {
		background-color: #3cb854;
	}
</style>